<template>
  <div class="profile-container">
    <!-- 用户信息头部 -->
    <div class="profile-header">
      <div class="user-info">
        <UserAvatar
          :user-id="userStore.userId"
          :avatar-url="userStore.userInfo?.avatar"
          :username="userStore.username"
          :nickname="userStore.nickname"
          size="extra-large"
          :clickable="true"
          @click="goToEditProfile"
        />
        <div class="user-details">
          <h2 class="user-nickname">{{ userStore.nickname }}</h2>
          <p class="user-username">@{{ userStore.username }}</p>
          <p v-if="userStore.userInfo?.signature" class="user-signature">
            {{ userStore.userInfo.signature }}
          </p>
        </div>
      </div>
      
      <div class="profile-actions">
        <el-button class="action-button" @click="goToEditProfile">
          编辑资料
        </el-button>
        <el-button class="action-button" @click="handleLogout">
          退出登录
        </el-button>
      </div>
    </div>
    
    <!-- 统计信息 -->
    <div class="profile-stats">
      <div class="stat-item">
        <div class="stat-number">{{ myVideos.length }}</div>
        <div class="stat-label">作品</div>
      </div>
      <div class="stat-item">
        <div class="stat-number">{{ formatCount(totalLikes) }}</div>
        <div class="stat-label">获赞</div>
      </div>
      <div class="stat-item">
        <div class="stat-number">{{ formatCount(totalViews) }}</div>
        <div class="stat-label">播放</div>
      </div>
    </div>
    
    <!-- 视频列表 -->
    <div class="video-list">
      <div class="list-header">
        <h3>我的作品</h3>
        <el-button 
          class="action-button small" 
          @click="$router.push('/upload')"
        >
          发布视频
        </el-button>
      </div>
      
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <div class="loading-text">加载中...</div>
      </div>
      
      <div v-else-if="myVideos.length === 0" class="empty-container">
        <el-icon :size="60">
          <VideoPlay />
        </el-icon>
        <div class="empty-text">还没有发布作品</div>
        <el-button class="action-button" @click="$router.push('/upload')">
          发布第一个视频
        </el-button>
      </div>
      
      <div v-else class="video-grid">
        <div
          v-for="video in myVideos"
          :key="video.id"
          class="video-item"
          @click="playVideo(video)"
        >
          <div class="video-cover">
            <img :src="video.coverUrl" :alt="video.title" />
            <div class="video-overlay">
              <el-icon class="play-icon" :size="30">
                <VideoPlay />
              </el-icon>
            </div>
            <div class="video-duration">
              {{ formatDuration(video.duration) }}
            </div>
          </div>
          <div class="video-info">
            <h4 class="video-title">{{ video.title }}</h4>
            <div class="video-stats">
              <span>{{ formatCount(video.viewCount) }} 播放</span>
              <span>{{ formatCount(video.likeCount) }} 点赞</span>
            </div>
          </div>
          
          <!-- 视频操作菜单 -->
          <el-dropdown class="video-menu" @command="handleVideoAction" @click.stop>
            <el-icon class="menu-icon" :size="16" @click.stop="testMenuClick($event, video)">
              <MoreFilled />
            </el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :command="{ action: 'delete', video }">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getMyVideos, deleteVideo } from '@/api/video'
import { formatCount, formatDuration } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VideoPlay, MoreFilled } from '@element-plus/icons-vue'
import UserAvatar from '@/components/UserAvatar/index.vue'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const myVideos = ref([])

// 计算总点赞数
const totalLikes = computed(() => {
  return myVideos.value.reduce((total, video) => total + video.likeCount, 0)
})

// 计算总播放数
const totalViews = computed(() => {
  return myVideos.value.reduce((total, video) => total + video.viewCount, 0)
})

// 加载我的视频
const loadMyVideos = async () => {
  loading.value = true
  
  try {
    const response = await getMyVideos({ current: 1, size: 100 })
    myVideos.value = response.data.records
  } catch (error) {
    ElMessage.error('加载视频失败')
  } finally {
    loading.value = false
  }
}

// 播放视频
const playVideo = (video) => {
  // TODO: 实现视频播放功能，可能需要跳转到专门的播放页面
  router.push(`/video/${video.id}`)
}

// 处理视频操作
const handleVideoAction = async ({ action, video }) => {
  console.log('菜单操作:', action, video)
  if (action === 'delete') {
    try {
      await ElMessageBox.confirm(
        '确定要删除这个视频吗？删除后无法恢复。',
        '确认删除',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      
      await deleteVideo(video.id)
      ElMessage.success('删除成功')
      
      // 从列表中移除
      const index = myVideos.value.findIndex(v => v.id === video.id)
      if (index > -1) {
        myVideos.value.splice(index, 1)
      }
      
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除视频失败:', error)
        ElMessage.error('删除失败')
      }
    }
  }
}

// 测试菜单点击
const testMenuClick = (event, video) => {
  event.stopPropagation()
  console.log('菜单图标被点击:', video)
}

// 跳转到编辑资料页面
const goToEditProfile = () => {
  router.push('/profile/edit')
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '确认退出',
      {
        type: 'warning'
      }
    )
    
    userStore.logout()
    router.push('/login')
    ElMessage.success('已退出登录')
  } catch (error) {
    // 用户取消
  }
}

// 组件挂载
onMounted(() => {
  loadMyVideos()
})
</script>

<style lang="scss" scoped>
.profile-container {
  width: 100vw;
  height: 100vh;
  background: $bg-dark;
  overflow-y: auto;
  padding-bottom: 80px; // 给底部导航栏留空间
}

.profile-header {
  padding: 20px;
  background: $bg-dark;
  color: $text-white;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  
  .user-info {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 20px;
    
    .user-details {
      flex: 1;
      
      .user-nickname {
        font-size: 24px;
        font-weight: 600;
        color: $text-white;
        margin: 0 0 8px 0;
      }
      
      .user-username {
        font-size: 14px;
        color: rgba(255, 255, 255, 0.7);
        margin: 0 0 8px 0;
      }
      
      .user-signature {
        font-size: 14px;
        color: rgba(255, 255, 255, 0.7);
        margin: 0;
        line-height: 1.4;
      }
    }
  }
  
  .profile-actions {
    display: flex;
    gap: 12px;
    
    :deep(.action-button) {
      background: rgba(255, 255, 255, 0.9) !important;
      color: #333 !important;
      border: 1px solid rgba(255, 255, 255, 0.2) !important;
      border-radius: $border-radius !important;
      font-weight: 500 !important;
      padding: 12px 20px !important;
      flex: 1;
      
      &:hover {
        background: rgba(255, 255, 255, 1) !important;
        color: #000 !important;
        border-color: rgba(255, 255, 255, 0.3) !important;
        transform: translateY(-1px);
      }
      
      &:active {
        transform: translateY(0);
      }
      
      &.small {
        padding: 8px 16px !important;
        font-size: 14px !important;
        flex: none;
      }
    }
  }
}

.profile-stats {
  display: flex;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  
  .stat-item {
    flex: 1;
    text-align: center;
    padding: 20px;
    border-right: 1px solid rgba(255, 255, 255, 0.1);
    
    &:last-child {
      border-right: none;
    }
    
    .stat-number {
      font-size: 20px;
      font-weight: 700;
      color: $text-white;
      margin-bottom: 4px;
    }
    
    .stat-label {
      font-size: 14px;
      color: rgba(255, 255, 255, 0.7);
    }
  }
}

.video-list {
  background: $bg-dark;
  min-height: calc(100vh - 300px);
  
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    
    h3 {
      margin: 0;
      color: $text-white;
      font-size: 18px;
      font-weight: 600;
    }
  }
  
  .loading-container,
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    gap: 16px;
    
    .loading-spinner {
      width: 40px;
      height: 40px;
      border: 3px solid rgba(255, 255, 255, 0.1);
      border-top: 3px solid $primary-color;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
    
    .loading-text,
    .empty-text {
      color: rgba(255, 255, 255, 0.7);
      font-size: 16px;
    }
    
    .el-icon {
      color: rgba(255, 255, 255, 0.5);
    }
  }
  
  .video-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 16px;
    padding: 20px;
    
    .video-item {
      position: relative;
      cursor: pointer;
      border-radius: $border-radius;
      overflow: hidden;
      transition: $transition-fast;
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid rgba(255, 255, 255, 0.1);
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
        background: rgba(255, 255, 255, 0.08);
        
        .video-overlay {
          opacity: 1;
        }
      }
      
      .video-cover {
        position: relative;
        width: 100%;
        height: 220px;
        background: rgba(255, 255, 255, 0.05);
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .video-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.5);
          display: flex;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: $transition-fast;
          
          .play-icon {
            color: $text-white;
          }
        }
        
        .video-duration {
          position: absolute;
          bottom: 8px;
          right: 8px;
          background: rgba(0, 0, 0, 0.7);
          color: $text-white;
          padding: 2px 6px;
          border-radius: 4px;
          font-size: 12px;
        }
      }
      
      .video-info {
        padding: 12px;
        
        .video-title {
          font-size: 14px;
          font-weight: 600;
          color: $text-white;
          margin: 0 0 8px 0;
          line-height: 1.3;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        
        .video-stats {
          display: flex;
          gap: 12px;
          font-size: 12px;
          color: rgba(255, 255, 255, 0.7);
        }
      }
      
      .video-menu {
        position: absolute;
        top: 8px;
        right: 8px;
        z-index: 10;
        
        .menu-icon {
          width: 24px;
          height: 24px;
          background: rgba(0, 0, 0, 0.5);
          color: $text-white;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: $transition-fast;
          
          &:hover {
            background: rgba(0, 0, 0, 0.7);
          }
        }
      }
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 响应式设计
@media (max-width: 768px) {
  .profile-header {
    padding: 16px;
    
    .user-info {
      margin-bottom: 16px;
      
      .user-details {
        .user-nickname {
          font-size: 20px;
        }
      }
    }
    
    .profile-actions {
      flex-direction: column;
      
      :deep(.action-button) {
        width: 100% !important;
        flex: none !important;
      }
    }
  }
  
  .profile-stats {
    .stat-item {
      padding: 16px;
      
      .stat-number {
        font-size: 18px;
      }
    }
  }
  
  .video-list {
    .video-grid {
      grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
      gap: 12px;
      padding: 16px;
      
      .video-item {
        .video-cover {
          height: 180px;
        }
        
        .video-info {
          padding: 8px;
          
          .video-title {
            font-size: 12px;
          }
          
          .video-stats {
            font-size: 10px;
          }
        }
      }
    }
  }
}
</style>

<!-- 全局样式确保dropdown菜单的z-index -->
<style>
.el-dropdown-menu {
  z-index: 9999 !important;
}
</style> 